package com.jungle.app.service.impl;

import com.jungle.app.domain.bo.UserBo;
import com.jungle.app.domain.vo.UserVo;
import com.jungle.app.repository.UserRepository;
import com.jungle.app.service.IUserService;
import com.jungle.common.core.domain.PageQuery;
import com.jungle.common.core.domain.entity.MyUser;
import com.jungle.common.core.page.TableDataInfo;
import com.jungle.common.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户信息Service业务层处理
 *
 * @author jungle
 * @date 2023-09-20
 */
@RequiredArgsConstructor
@Service
public class UserServiceImpl implements IUserService {

    private final UserRepository repository;

    /**
     * 查询用户信息
     */
    @Override
    public UserVo queryById(String id){
        return repository.findById(id).map(v -> com.jungle.common.utils.BeanCopyUtils.copy(v, UserVo.class)).orElse(null);
    }

    /**
     * 查询用户信息列表
     */
    @Override
    public TableDataInfo<UserVo> queryPageList(UserBo bo, PageQuery pageQuery) {
        Page<MyUser> result = repository.findAll(getSpecification(bo), pageQuery.pageable());
        return TableDataInfo.build(result, UserVo.class);
    }

    /**
     * 查询用户信息列表
     */
    @Override
    public List<UserVo> queryList(UserBo bo) {
        return repository.findAll(getSpecification(bo)).stream()
            .map(v -> com.jungle.common.utils.BeanCopyUtils.copy(v, UserVo.class))
            .collect(Collectors.toList());
    }

    private Specification<MyUser> getSpecification(UserBo bo) {
        return (root, query, cb) -> {
            Map<String, Object> params = bo.getParams();
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(bo.getAddress())) {
                    predicates.add(cb.equal(root.get("address"), bo.getAddress()));
            }
            if (StringUtils.isNotBlank(bo.getAvatar())) {
                    predicates.add(cb.equal(root.get("avatar"), bo.getAvatar()));
            }
            if (StringUtils.isNotBlank(bo.getHobby())) {
                    predicates.add(cb.equal(root.get("hobby"), bo.getHobby()));
            }
            if (StringUtils.isNotBlank(bo.getIdNumber())) {
                    predicates.add(cb.equal(root.get("idNumber"), bo.getIdNumber()));
            }
            if (StringUtils.isNotBlank(bo.getNickName())) {
                    predicates.add(cb.like(root.get("nickName"), "%" + bo.getNickName() + "%"));
            }
            if (StringUtils.isNotBlank(bo.getOpenid())) {
                    predicates.add(cb.equal(root.get("openid"), bo.getOpenid()));
            }
            if (StringUtils.isNotBlank(bo.getPassword())) {
                    predicates.add(cb.equal(root.get("password"), bo.getPassword()));
            }
            if (StringUtils.isNotBlank(bo.getPersonality())) {
                    predicates.add(cb.equal(root.get("personality"), bo.getPersonality()));
            }
            if (StringUtils.isNotBlank(bo.getPhoneNumber())) {
                    predicates.add(cb.equal(root.get("phoneNumber"), bo.getPhoneNumber()));
            }
            if (StringUtils.isNotBlank(bo.getRealName())) {
                    predicates.add(cb.like(root.get("realName"), "%" + bo.getRealName() + "%"));
            }
            if (bo.getSex() != null) {
                    predicates.add(cb.equal(root.get("sex"), bo.getSex()));
            }
            if (bo.getStatus() != null) {
                    predicates.add(cb.equal(root.get("status"), bo.getStatus()));
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };
    }

    /**
     * 新增用户信息
     */
    @Override
    public Boolean insertByBo(UserBo bo) {
        //MD5加密处理
        bo.setPassword(DigestUtils.md5DigestAsHex(bo.getPassword().getBytes()));
        MyUser add = com.jungle.common.utils.BeanCopyUtils.copy(bo, MyUser.class);
        validEntityBeforeSave(add);
        repository.saveAndFlush(add);
        bo.setId(add.getId());
        return true;
    }

    /**
     * 修改用户信息
     */
    @Override
    public Boolean updateByBo(UserBo bo) {
        MyUser hadUser = repository.findById(bo.getId()).get();
        MyUser update = com.jungle.common.utils.BeanCopyUtils.copy(bo, MyUser.class);
        validEntityBeforeSave(update);
        update.setCreateTime(hadUser.getCreateTime());//LocalDateTime转Date
        return repository.save(update) != null;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(MyUser entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除用户信息
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        repository.deleteAllById(ids);
        return true;
    }

}
